﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtNetwork>
#include <QImageReader>
#include <QMessageBox>

QString MainWindow::getLocalIP()
{//获取本机IPv4地址
    QString hostName=QHostInfo::localHostName();//本地主机名
    QHostInfo   hostInfo=QHostInfo::fromName(hostName);
    QString   localIP="";

    QList<QHostAddress> addList=hostInfo.addresses();//

    if (!addList.isEmpty())
    for (int i=0;i<addList.count();i++)
    {
        QHostAddress aHost=addList.at(i);
        if (QAbstractSocket::IPv4Protocol==aHost.protocol())
        {
            localIP=aHost.toString();
            break;
        }
    }
    return localIP;
}

void MainWindow::closeEvent(QCloseEvent *event)
{//关闭窗口时停止监听
    if (tcpServer->isListening())
        tcpServer->close();;//停止网络监听
    event->accept();
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    LabListen=new QLabel("监听状态:");
    LabListen->setMinimumWidth(150);
    ui->statusBar->addWidget(LabListen);

    LabSocketState=new QLabel("Socket状态：");//
    LabSocketState->setMinimumWidth(200);
    ui->statusBar->addWidget(LabSocketState);

    QString localIP=getLocalIP();//本机IP
    this->setWindowTitle(this->windowTitle()+"----本机IP："+localIP);
    ui->comboIP->addItem(localIP);

    tcpServer=new QTcpServer(this);
    tcpSocket=new QTcpSocket(this);
//    file_tcpSocket=new QTcpSocket(this); //创建socket变量
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));
    fileBytes = sentBytes = restBytes = 0;

    //语音对讲
    //录音发送
    udpSocket= new QUdpSocket(this);
//    udpSocket->bind(QHostAddress::Any,10004);//绑定10004端口
    udpSocket->bind(QHostAddress(localIP), 10004);
//    myAudio= new AudioThread();
//    connect(myAudio->inputDevice,SIGNAL(readyRead()),this,SLOT(MicroPhoneonReadyRead()));
     //槽函数，当inputDevice收到input写入的音频数据之后,调用onReadyRead函数，发送数据到目标主机上
//    myAudio->start();

    //接收音频播放
    myAudioRec =new AudioRecThread();
    connect(udpSocket,SIGNAL(readyRead()),this,SLOT(RecreadyReadSlot()));
    //收到网络数据报就开始往outputDevice写入，进行播放
    myAudioRec->start();
    myAudioRec->Pause();
//    connect(ui->comboIP,SIGNAL(currentTextChanged(QString)),this,SLOT(AddIPChange()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onNewConnection()
{
//    ui->plainTextEdit->appendPlainText("有新连接");
    tcpSocket = tcpServer->nextPendingConnection(); //创建socket

    connect(tcpSocket, SIGNAL(connected()),
            this, SLOT(onClientConnected()));
    onClientConnected();//

    connect(tcpSocket, SIGNAL(disconnected()),
            this, SLOT(onClientDisconnected()));

    connect(tcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),
            this,SLOT(onSocketStateChange(QAbstractSocket::SocketState)));
    onSocketStateChange(tcpSocket->state());

    connect(tcpSocket,SIGNAL(readyRead()),
            this,SLOT(onfileSocketReadyRead()));
}

void MainWindow::onSocketStateChange(QAbstractSocket::SocketState socketState)
{//socket状态变化时
    switch(socketState)
    {
    case QAbstractSocket::UnconnectedState:
        LabSocketState->setText("scoket状态：UnconnectedState");
        break;
    case QAbstractSocket::HostLookupState:
        LabSocketState->setText("scoket状态：HostLookupState");
        break;
    case QAbstractSocket::ConnectingState:
        LabSocketState->setText("scoket状态：ConnectingState");
        break;

    case QAbstractSocket::ConnectedState:
        LabSocketState->setText("scoket状态：ConnectedState");
        break;

    case QAbstractSocket::BoundState:
        LabSocketState->setText("scoket状态：BoundState");
        break;

    case QAbstractSocket::ClosingState:
        LabSocketState->setText("scoket状态：ClosingState");
        break;

    case QAbstractSocket::ListeningState:
        LabSocketState->setText("scoket状态：ListeningState");
    }
}

void MainWindow::onClientConnected()
{//客户端接入时
    ui->plainTextEdit->appendPlainText("**client socket connected");
    ui->plainTextEdit->appendPlainText("**peer address:"+
                                   tcpSocket->peerAddress().toString());
    ui->plainTextEdit->appendPlainText("**peer port:"+
                                   QString::number(tcpSocket->peerPort()));
}

void MainWindow::onClientDisconnected()
{//客户端断开连接时
    ui->plainTextEdit->appendPlainText("**client socket disconnected");
    tcpSocket->deleteLater();
    //    deleteLater();//QObject::deleteLater();
}

void MainWindow::onfileSocketReadyRead()
{
    QByteArray temp = tcpSocket->readAll();
//    qDebug() << "temp : " << temp;
    receivedData.append(temp);
    while(receivedData.size()>0){
        if(packetLength == 0)
        {
              int packetLength = receivedData.mid(2,4).toHex().toInt(NULL,16);
//              qDebug() << "packetLength : " << packetLength;
//              qDebug() << "receivedData.size : " << receivedData.size( );
//              if(receivedData.size() >= (3 + packetLength))     //第N条报文读取完毕
              if(receivedData.size() >= (6 + packetLength))
              {
                  QByteArray receivedData_per = receivedData.mid(0,6+packetLength);  //第N条有效报文
                  receivedData = receivedData.mid(6 + packetLength);     //剩下的未读报文
                  deal_with_file(receivedData_per);      //解析第N条报文
                  packetLength = 0;
              }
              if(receivedData.size() < (6 + packetLength))
              {
                  break;
              }
        }
    }
}

void MainWindow::deal_with_file(QByteArray fileserreceive_per)
{
//    qDebug()<<"fileserreceive_per"<<fileserreceive_per;
    int file_mark = fileserreceive_per.mid(1,1).toHex().toInt(NULL,16);
    if(file_mark==16)
    {
        QByteArray message_receive=fileserreceive_per.mid(6,fileserreceive_per.size()-6);
        ui->plainTextEdit->appendPlainText("[接收：] "+message_receive);
    }
    if(file_mark==49)
    {
        data_length_per_sum=0;
        fileBytes = sentBytes = restBytes = 0;
        receive_fileSize=0;
        receive_fileName_length=fileserreceive_per.mid(6,2).toHex().toInt(NULL,16);
        QByteArray receive_fileName=fileserreceive_per.mid(8,receive_fileName_length);
//        qDebug()<<"receive_fileName"<<receive_fileName;
        ui->plainTextEdit->appendPlainText("[接收：] "+receive_fileName);
        receive_fileSize=fileserreceive_per.mid(8+receive_fileName_length,4).toHex().toInt(NULL,16);
//        qDebug()<<"receive_fileSize"<<receive_fileSize;
        file_receive = new QFile(receive_fileName);
        file_receive->open(QFile::WriteOnly);
//        qDebug()<<"voice_file_0x31接收成功,发送voice_file_0x32;创建目标文件:" << receive_fileName;
        voice_file_0x32();
    }
    if(file_mark==50)
    {
//        qDebug()<<"voice_file_0x32已收到。";
        voice_file_0x33();
    }
    if(file_mark==51)
    {
//        qDebug()<<"接收到voice_file_0x33。";
        int data_length_per=fileserreceive_per.mid(2,4).toHex().toInt(NULL,16);
//        qDebug()<<"data_length_per"<<data_length_per;
        QByteArray receive_fileContent_per=fileserreceive_per.mid(6,data_length_per);
//        qDebug()<<"receive_fileContent_per.size()"<<receive_fileContent_per.size();
//        qDebug()<<"data_length_per_sum : " << data_length_per_sum;
        if(data_length_per_sum<receive_fileSize)
        {
            file_receive->write(receive_fileContent_per);
            data_length_per_sum=data_length_per_sum+data_length_per;
//            qDebug()<<"data_length_per_sum : " << data_length_per_sum;
//            qDebug()<< "receive_fileSize : " << receive_fileSize;
        }
        if(data_length_per_sum==receive_fileSize){
            file_receive->close();
            data_length_per_sum=0;
//            qDebug()<<"0x43接收成功,获取文件内容并保存";
            voice_file_0x35();
            QMessageBox::about(NULL,"文件","文件接收成功");
        }
    }
    if(file_mark==52)
    {
//        qDebug()<<"voice_file_0x34已收到";
    }
    if (file_mark==53) {
//        qDebug()<<"0x34接收成功,文件发送结束";
//        qDebug()<<"voice_file_0x35已收到";
        QMessageBox::about(NULL,"文件","文件发送成功");
    }

    if(file_mark==65)
    {
        data_length_per_sum=0;
        fileBytes = sentBytes = restBytes = 0;
        receive_fileSize=0;
        receive_fileName_length=fileserreceive_per.mid(6,2).toHex().toInt(NULL,16);
        QByteArray receive_fileName=fileserreceive_per.mid(8,receive_fileName_length);
//        qDebug()<<"receive_fileName"<<receive_fileName;
        ui->plainTextEdit->appendPlainText("[接收：] "+receive_fileName);
        receive_fileSize=fileserreceive_per.mid(8+receive_fileName_length,4).toHex().toInt(NULL,16);
//        qDebug()<<"receive_fileSize"<<receive_fileSize;
        file_receive = new QFile(receive_fileName);
        file_receive->open(QFile::WriteOnly);
//        qDebug()<<"0x31接收成功,发送0x32;创建目标文件:" << receive_fileName;

        file_0x42();

    }
    if(file_mark==66)
    {
//        qDebug()<<"file_0x42已收到。";
        file_0x43();

    }
    if(file_mark==67)
    {
//        qDebug()<<"接收到file_0x43。";
        int data_length_per=fileserreceive_per.mid(2,4).toHex().toInt(NULL,16);
//        qDebug()<<"data_length_per"<<data_length_per;
        QByteArray receive_fileContent_per=fileserreceive_per.mid(6,data_length_per);
//        qDebug()<<"receive_fileContent_per.size()"<<receive_fileContent_per.size();
//        qDebug()<<"data_length_per_sum : " << data_length_per_sum;
        if(data_length_per_sum<receive_fileSize)
        {
            file_receive->write(receive_fileContent_per);
            data_length_per_sum=data_length_per_sum+data_length_per;
//            qDebug()<<"data_length_per_sum : " << data_length_per_sum;
//            qDebug()<< "receive_fileSize : " << receive_fileSize;
        }
        if(data_length_per_sum==receive_fileSize){
            file_receive->close();
            data_length_per_sum=0;
//            qDebug()<<"0x43接收成功,获取文件内容并保存";
            file_0x45();
            QMessageBox::about(NULL,"文件","文件接收成功");
        }
    }
    if(file_mark==68)
    {
//        qDebug()<<"file_0x44已收到";
    }
    if (file_mark==69) {
//        qDebug()<<"0x34接收成功,文件发送结束";
//        qDebug()<<"file_0x45已收到";
        QMessageBox::about(NULL,"文件","文件发送成功");
    }
}

void MainWindow::file_0x42()
{
    QByteArray data;
    data.append(0x01);
    int data_length=data.size();
    QByteArray file_array;
    file_array.append(0xCE);
    file_array.append(0x42);
    file_array.append((data_length & 0xff000000) >>24);
    file_array.append((data_length & 0x00ff0000) >>16);
    file_array.append((data_length & 0x0000ff00) >>8);
    file_array.append(data_length & 0xff);
    file_array.append(data);
    tcpSocket->write(file_array);
//    qDebug()<<"file_0x42:"<<file_array;
//    qDebug()<<"file_0x42已发送。";
}

void MainWindow::file_0x43()
{
    restBytes=fileBytes;
//    int fileContent_sequence=1;
    while(1){
    if(restBytes>0){
        QByteArray buf =file->read(1200);
        QByteArray file_fun;
        file_fun.append(0xCE);
        file_fun.append(0x43);
        file_fun.append((buf.size() & 0xff000000) >>24);
        file_fun.append((buf.size() & 0x00ff0000) >>16);
        file_fun.append((buf.size() & 0x0000ff00) >>8);
        file_fun.append(buf.size() & 0xff);
        file_fun.append(buf);
        tcpSocket->write(file_fun);
//        qDebug()<< file_fun;
        restBytes=restBytes-buf.size();
//        qDebug()<< restBytes;
        sentBytes=sentBytes+buf.size();
//        qDebug()<< sentBytes;
    }
    if(sentBytes == fileBytes)
    {
        file->close();
        aFile_str.clear(); // 清空文件名
        sentBytes=0;
//        qDebug()<< "file_0x43已发送完成。";
        file_0x44();
        break;
    }
    }
}

void MainWindow::file_0x44()
{
    QByteArray data;
    data.append(0x01);
    int data_length=data.size();
    QByteArray file_array;
    file_array.append(0xCE);
    file_array.append(0x44);
    file_array.append((data_length & 0xff000000) >>24);
    file_array.append((data_length & 0x00ff0000) >>16);
    file_array.append((data_length & 0x0000ff00) >>8);
    file_array.append(data_length & 0xff);
    file_array.append(data);
    tcpSocket->write(file_array);
//    qDebug()<<"file_0x44已发送。";
}

void MainWindow::file_0x45()
{
    QByteArray data;
    data.append(0x01);
    int data_length=data.size();
    QByteArray file_array;
    file_array.append(0xCE);
    file_array.append(0x45);
    file_array.append((data_length & 0xff000000) >>24);
    file_array.append((data_length & 0x00ff0000) >>16);
    file_array.append((data_length & 0x0000ff00) >>8);
    file_array.append(data_length & 0xff);
    file_array.append(data);
    tcpSocket->write(file_array);
//    qDebug()<<"file_0x45已发送。";
}

void MainWindow::on_actStart_triggered()
{//开始监听
    ui->comboIP->setEnabled(false);
    ui->spinPort->setEnabled(false);
    QString     IP=ui->comboIP->currentText();//IP地址
    quint16     port=ui->spinPort->value();//端口
    QHostAddress    addr(IP);
    tcpServer->listen(addr,port);//
    ui->plainTextEdit->appendPlainText("**开始监听...");
    ui->plainTextEdit->appendPlainText("**服务器地址："
                       +tcpServer->serverAddress().toString());
    ui->plainTextEdit->appendPlainText("**服务器端口："
                       +QString::number(tcpServer->serverPort()));

    ui->actStart->setEnabled(false);
    ui->actStop->setEnabled(true);

    LabListen->setText("监听状态：正在监听");
}

void MainWindow::on_actStop_triggered()
{//停止监听
    if (tcpServer->isListening()) //tcpServer正在监听
    {
        tcpServer->close();//停止监听
        ui->actStart->setEnabled(true);
        ui->actStop->setEnabled(false);
        LabListen->setText("监听状态：已停止监听");
    }
    ui->comboIP->setEnabled(true);
    ui->spinPort->setEnabled(true);
}

void MainWindow::on_actClear_triggered()
{
    ui->plainTextEdit->clear();
}

void MainWindow::on_btnSend_clicked()
{//发送数据
    QString  msg=ui->editMsg->text();
    ui->plainTextEdit->appendPlainText("[发送：] "+msg);
    ui->editMsg->clear();
    ui->editMsg->setFocus();

    QByteArray  str=msg.toUtf8();
//    str.append('\n');
    QByteArray message;
    message.append(0xCE);
    message.append(0x10);
    message.append((str.size() & 0xff000000) >>24);
    message.append((str.size() & 0x00ff0000) >>16);
    message.append((str.size() & 0x0000ff00) >>8);
    message.append(str.size() & 0xff);
    message.append(str);
    tcpSocket->write(message);
}

void MainWindow::on_actHostInfo_triggered()
{//获取本机地址
    QString hostName=QHostInfo::localHostName();//本地主机名
    ui->plainTextEdit->appendPlainText("本机主机名："+hostName+"\n");
    QHostInfo   hostInfo=QHostInfo::fromName(hostName);

    QList<QHostAddress> addList=hostInfo.addresses();//
    if (!addList.isEmpty())
    for (int i=0;i<addList.count();i++)
    {
        QHostAddress aHost=addList.at(i);
        if (QAbstractSocket::IPv4Protocol==aHost.protocol())
        {
            QString IP=aHost.toString();
            ui->plainTextEdit->appendPlainText("本机IP地址："+aHost.toString());
            if (ui->comboIP->findText(IP)<0)
                ui->comboIP->addItem(IP);
        }
    }

}

void MainWindow::on_btn_voice_pressed()
{
    QAudioFormat defaultAudioFormat; //缺省格式
    defaultAudioFormat.setSampleRate(8000);
    defaultAudioFormat.setChannelCount(1);
    defaultAudioFormat.setSampleSize(8);
    defaultAudioFormat.setCodec("audio/pcm");
    defaultAudioFormat.setByteOrder(QAudioFormat::LittleEndian);
    defaultAudioFormat.setSampleType(QAudioFormat::UnSignedInt);
    voiceInput = new QAudioInput(defaultAudioFormat);

    destinationFile.setFileName("input.pcm");
    destinationFile.open( QIODevice::WriteOnly | QIODevice::Truncate );
    voiceInput->start(&destinationFile);
//    qDebug()<< "正在录音";
}

void MainWindow::on_btn_voice_released()
{
    record_stop();
    voice_file_0x31();
}

void MainWindow::voice_file_0x31()
{
    QFileInfo fileInfo("input.pcm");
    file_voice=new QFile("input.pcm");
    file_voice->open(QIODevice::ReadOnly);

    QString fileName_str=fileInfo.fileName();
    QByteArray byte_array_fileName=fileName_str.toUtf8();
    int fileName_length=byte_array_fileName.size();

    fileBytes=fileInfo.size();
    qDebug()<<"fileBytes:"<<fileBytes;
    file=new QFile(aFile_str);
    file->open(QIODevice::ReadOnly);
//    QByteArray buf_file =file->readAll();
    QByteArray data;
    data.append((fileName_length & 0xff00) >>8);
    data.append(fileName_length & 0xff);
    data.append(byte_array_fileName);
    data.append((fileBytes & 0xff000000) >>24);
    data.append((fileBytes & 0x00ff0000) >>16);
    data.append((fileBytes & 0x0000ff00) >>8);
    data.append(fileBytes & 0xff);
    int data_length=data.size();
    QByteArray file_array;
    file_array.append(0xCE);
    file_array.append(0x31);
    file_array.append((data_length & 0xff000000) >>24);
    file_array.append((data_length & 0x00ff0000) >>16);
    file_array.append((data_length & 0x0000ff00) >>8);
    file_array.append(data_length & 0xff);
    file_array.append(data);
    tcpSocket->write(file_array);
    ui->plainTextEdit->appendPlainText("[发送：] " + byte_array_fileName);
//    qDebug()<<"file_array:"<<file_array;
//    qDebug()<<"语音文件已选择！";
}

void MainWindow::voice_file_0x32()
{
    QByteArray data;
    data.append(0x01);
    int data_length=data.size();
    QByteArray file_array;
    file_array.append(0xCE);
    file_array.append(0x32);
    file_array.append((data_length & 0xff000000) >>24);
    file_array.append((data_length & 0x00ff0000) >>16);
    file_array.append((data_length & 0x0000ff00) >>8);
    file_array.append(data_length & 0xff);
    file_array.append(data);
    tcpSocket->write(file_array);
//    qDebug()<<"voice_file_0x32:"<<file_array;
}

void MainWindow::voice_file_0x33()
{
    restBytes=fileBytes;
//    int fileContent_sequence=1;
    while(1){
    if(restBytes>0){
        QByteArray buf =file_voice->read(1200);
        QByteArray file_fun;
        file_fun.append(0xCE);
        file_fun.append(0x33);
        file_fun.append((buf.size() & 0xff000000) >>24);
        file_fun.append((buf.size() & 0x00ff0000) >>16);
        file_fun.append((buf.size() & 0x0000ff00) >>8);
        file_fun.append(buf.size() & 0xff);
        file_fun.append(buf);
        tcpSocket->write(file_fun);
//        qDebug()<< file_fun;
        restBytes=restBytes-buf.size();
//        qDebug()<< restBytes;
        sentBytes=sentBytes+buf.size();
//        qDebug()<< sentBytes;
    }
    if(sentBytes == fileBytes)
    {
        file->close();
        aFile_str.clear(); // 清空文件名
        sentBytes=0;
//        qDebug()<< "voice_file_0x33已发送完成。";
        voice_file_0x34();
        break;
    }
    }
}

void MainWindow::voice_file_0x34()
{
    QByteArray data;
    data.append(0x01);
    int data_length=data.size();
    QByteArray file_array;
    file_array.append(0xCE);
    file_array.append(0x34);
    file_array.append((data_length & 0xff000000) >>24);
    file_array.append((data_length & 0x00ff0000) >>16);
    file_array.append((data_length & 0x0000ff00) >>8);
    file_array.append(data_length & 0xff);
    file_array.append(data);
    tcpSocket->write(file_array);
//    qDebug()<<"voice_file_0x34已发送。";
}

void MainWindow::voice_file_0x35()
{
    QByteArray data;
    data.append(0x01);
    int data_length=data.size();
    QByteArray file_array;
    file_array.append(0xCE);
    file_array.append(0x35);
    file_array.append((data_length & 0xff000000) >>24);
    file_array.append((data_length & 0x00ff0000) >>16);
    file_array.append((data_length & 0x0000ff00) >>8);
    file_array.append(data_length & 0xff);
    file_array.append(data);
    tcpSocket->write(file_array);
//    qDebug()<<"voice_file_0x35已发送。";
}

void MainWindow::record_stop()
{
    voiceInput->stop();
    voiceInput->deleteLater();
    destinationFile.close();
    delete voiceInput;
}
void MainWindow::on_btn_voice_speak_clicked()
{
    QAudioFormat defaultAudioFormat; //缺省格式
    defaultAudioFormat.setSampleRate(8000);
    defaultAudioFormat.setChannelCount(1);
    defaultAudioFormat.setSampleSize(8);
    defaultAudioFormat.setCodec("audio/pcm");
    defaultAudioFormat.setByteOrder(QAudioFormat::LittleEndian);
    defaultAudioFormat.setSampleType(QAudioFormat::UnSignedInt);

    QAudioOutput *outaudio=new QAudioOutput(defaultAudioFormat,0);
    QIODevice *io=outaudio->start();

    int size=outaudio->periodSize();
    char *buf=new char[size];

    FILE *fp=fopen("input.pcm","rb");
    while (!feof(fp))
    {
        if(outaudio->bytesFree()<size)
        {
            QThread::msleep(1);
            continue;
        }
        int len=fread(buf,1,size,fp);
        if (len<=0) break;
        io->write(buf,len);
    }
    fclose(fp);
    delete buf;
    buf=0;
}

void MainWindow::on_btn_file_clicked()
{
    QFile File;
    QString curDir=QDir::currentPath();
    aFile_str=QFileDialog::getOpenFileName(this,"打开一个文件",curDir,"所有文件(*.*)");
    File.setFileName(aFile_str);

    QFileInfo fileInfo(aFile_str);
    QString fileName_str=fileInfo.fileName();
    QByteArray byte_array_fileName=fileName_str.toUtf8();

    int fileName_length=byte_array_fileName.size();

    fileBytes=fileInfo.size();
//    qDebug()<<"fileBytes:"<<fileBytes;
    file=new QFile(aFile_str);
    file->open(QIODevice::ReadOnly);
//    QByteArray buf_file =file->readAll();
    QByteArray data;
    data.append((fileName_length & 0xff00) >>8);
    data.append(fileName_length & 0xff);
    data.append(byte_array_fileName);
    data.append((fileBytes & 0xff000000) >>24);
    data.append((fileBytes & 0x00ff0000) >>16);
    data.append((fileBytes & 0x0000ff00) >>8);
    data.append(fileBytes & 0xff);
    int data_length=data.size();
    QByteArray file_array;
    file_array.append(0xCE);
    file_array.append(0x41);
    file_array.append((data_length & 0xff000000) >>24);
    file_array.append((data_length & 0x00ff0000) >>16);
    file_array.append((data_length & 0x0000ff00) >>8);
    file_array.append(data_length & 0xff);
    file_array.append(data);
    tcpSocket->write(file_array);
    ui->plainTextEdit->appendPlainText("[发送：] " + byte_array_fileName);
//    qDebug()<<"file_array:"<<file_array;
//    qDebug()<<"文件已选择！";
}

void MainWindow::on_btn_picture_clicked()
{
    on_btn_file_clicked();
}

void MainWindow::MicroPhoneonReadyRead()
{
//    qDebug()<<"It's sending audio!"<<endl;
    AddIp =ui->comboIP->currentText();
//    qDebug()<<"AddIp："<<AddIp;
    video vp;
    memset(&vp,0,sizeof(vp));
    //读取音频
    vp.lens =myAudio->inputDevice->read(vp.audiodata,1024);//读取音频
    QHostAddress destaddr;
    destaddr.setAddress(AddIp);
    //将此结构体发送给目标主机，端口是10004
    udpSocket->writeDatagram((const char*)&vp,sizeof(vp),destaddr,10004);
//    qDebug()<<"语音已发送..."<<endl;
}

void MainWindow::RecreadyReadSlot()//Udp接受到数据，播放音频
{
    myAudioRec->Resume();
    while(udpSocket->hasPendingDatagrams())
    {
        QHostAddress senderip;
        quint16 senderport;
        video vp;
        memset(&vp,0,sizeof(vp));
        udpSocket->readDatagram((char*)&vp,sizeof(vp),&senderip,&senderport);
        myAudioRec->outputDevice->write(vp.audiodata,vp.lens);
    }
    myAudioRec->Pause();
//    qDebug()<<"语音已接收..."<<endl;
}

//void MainWindow::AddIPChange()//COMbox
//{
//    AddIp =ui->comboIP->currentText();
//    qDebug()<<"AddIp："<<AddIp;
//}

void MainWindow::on_btn_telephone_clicked()
{
    if(ui->btn_telephone->text() == tr("对讲"))
      {
         // AddIp = ui->lineEdit->text();
          //myAudio->Resume();
        myAudio= new AudioThread();
        connect(myAudio->inputDevice,SIGNAL(readyRead()),this,SLOT(MicroPhoneonReadyRead()));
         //槽函数，当inputDevice收到input写入的音频数据之后,调用onReadyRead函数，发送数据到目标主机上
        myAudio->start();
        ui->btn_telephone->setText("挂断");
        qDebug()<<"通话中......";
      }
      else
      {
         myAudio->stop();
//        myAudioRec->Pause();
        qDebug()<<"通话已挂断";
//        AddIp = "无";
        ui->btn_telephone->setText("对讲");
      }
}
